package git.soulbgm.pojo.dto;

import git.soulbgm.utils.CmdUtil;
import git.soulbgm.utils.NumberUtil;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * 程序存活情况信息
 *
 * @author SoulBGM
 * @date 2019/10/10 11:03
 */
public class AliveInfo {

    /**
     * 进程名称
     */
    private String name;
    /**
     * 启动时间
     */
    private Long startupTime = 0L;
    /**
     * PID
     */
    private Integer pid = 0;
    /**
     * 是否存活
     */
    private Boolean status;

    /**
     * 设置存活情况为未存活
     *
     * @param name 程序名字
     * @return {@link AliveInfo}
     */
    public static AliveInfo down(String name) {
        AliveInfo info = new AliveInfo();
        info.setName(name);
        info.setStartupTime(0L);
        info.setStatus(false);
        return info;
    }

    /**
     * 格式化启动时间字段 Linux版本
     */
    private final static DateTimeFormatter FORMATTER_LINUX = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy", Locale.UK);
    /**
     * 格式化启动时间字段 Win版本
     */
    private final static DateTimeFormatter FORMATTER_WIN = DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.UK);

    /**
     * 设置存活情况为存活
     *
     * @param name   的名字
     * @param osName 系统
     * @param date   日期
     * @return {@link AliveInfo}
     */
    public static AliveInfo running(String name, String osName, String date, String pid) {
        AliveInfo info = new AliveInfo();
        info.setName(name);
        if (date != null && !"".equals(date.trim())) {
            LocalDateTime dateTime = LocalDateTime.parse(date, CmdUtil.OS_LINUX.equals(osName) ? FORMATTER_LINUX : FORMATTER_WIN);
            info.setStartupTime(dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        }
        if (NumberUtil.isInteger(pid)) {
            info.setPid(Integer.parseInt(pid.trim()));
        }
        info.setStatus(true);
        return info;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getStartupTime() {
        return startupTime;
    }

    public void setStartupTime(Long startupTime) {
        this.startupTime = startupTime;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }
}
